
#include <gtest/gtest.h>

#include <boost/asio/io_context.hpp>

#include "KVCommand.h"
#include "KVStateGRpc.h"
#include "KVStateMachine.h"
#include "Server.h"
#include "raft_core/RaftCoreGrpc.h"


TEST(KV_RAFT, SERVERTEST) {
    // 启动状态机
    auto kv_state_machine = std::make_shared<KVStateMachine>();
    auto kv_state_grpc = std::make_unique<KVStateGrpc>();
    std::thread t1([&] {
        kv_state_grpc->start(kv_state_machine);
    });
    t1.detach();

    // 启动 raft 节点
    auto kv_command_core = std::make_shared<KVCommand>();
    auto raft_core_grpc = std::make_shared<raft::core::RaftCoreGrpc>();
    std::thread t2([&] {
        raft_core_grpc->start(kv_state_machine, kv_command_core);
    });
    t2.detach();

    // 启动中间件
    boost::asio::io_context ioContext;
    // 创建服务器实例，监听 80 端口
    Server server(ioContext, 8888);

    // 获取硬件并发线程数并适当增加一些线程数
    const unsigned int numThreads = std::thread::hardware_concurrency() * 2;
    // 创建多个线程执行ioContext.run()
    std::vector<std::thread> threads;
    for (unsigned int i = 0; i < numThreads; ++i) {
        threads.emplace_back([&ioContext]() {
            // 运行 io_context，处理异步操作
            ioContext.run();
        });
    }
    for (auto &thread: threads) {
        thread.join();
    }

    std::this_thread::sleep_for(std::chrono::seconds(1000));
}